package com.two.screen.water.balance.ui.activity

import android.annotation.SuppressLint
import android.app.AlertDialog
import android.content.Intent
import android.graphics.Typeface
import android.os.BatteryManager
import android.os.Bundle
import android.view.Gravity
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.RelativeLayout
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.core.view.isVisible
import androidx.recyclerview.widget.*
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.NetworkUtils
import com.chad.library.adapter.base.BaseItemDraggableAdapter
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.BaseViewHolder
import com.chad.library.adapter.base.callback.ItemDragAndSwipeCallback
import com.chad.library.adapter.base.listener.OnItemDragListener
import com.google.gson.reflect.TypeToken
import com.gyf.barlibrary.BarHide
import com.gyf.barlibrary.ImmersionBar
import com.jakewharton.rxbinding2.view.RxView
import com.lzf.easyfloat.EasyFloat
import com.lzf.easyfloat.enums.ShowPattern
import com.lzf.easyfloat.permission.PermissionUtils
import com.two.screen.water.balance.R
import com.two.screen.water.balance.bean.*
import com.two.screen.water.balance.bean.database.*
import com.two.screen.water.balance.bean.database.OrderProductDB.UNIT_TYPE_TIMES
import com.two.screen.water.balance.image.ImageManger
import com.two.screen.water.balance.listener.ApiCallBack
import com.two.screen.water.balance.net.api.CateProductApi
import com.two.screen.water.balance.net.api.DataApi
import com.two.screen.water.balance.net.api.NormalApi
import com.two.screen.water.balance.net.api.OrderApi
import com.two.screen.water.balance.net.api.OrderApi.ORDER_TYPE_PENDING
import com.two.screen.water.balance.net.api.OrderApi.PAY_TYPE_NONE
import com.two.screen.water.balance.net.observer.DialogObserver
import com.two.screen.water.balance.print.PrinterAll
import com.two.screen.water.balance.print.bean.PrintOrderBean
import com.two.screen.water.balance.ui.App
import com.two.screen.water.balance.ui.activity.base.BaseActivity
import com.two.screen.water.balance.ui.service.AppService
import com.two.screen.water.balance.ui.service.BatteryChangedBean
import com.two.screen.water.balance.utils.*
import com.two.screen.water.balance.utils.eventbus.Event
import com.two.screen.water.balance.utils.eventbus.EventBusUtil
import com.two.screen.water.balance.utils.eventbus.EventCode
import com.two.screen.water.balance.utils.eventbus.EventCode.Companion.AI_RETURN_INFO
import com.two.screen.water.balance.utils.eventbus.EventCode.Companion.COLLECT_MONEY_SUCCESS
import com.two.screen.water.balance.utils.eventbus.EventCode.Companion.PENDING_ORDER_COLLECT_MONEY
import com.two.screen.water.balance.utils.eventbus.EventCode.Companion.PENDING_ORDER_EDIT_AGAIN
import com.two.screen.water.balance.utils.eventbus.EventCode.Companion.WEIGHT_DATA_ALL
import com.two.screen.water.balance.widget.dialog.EditOrderGoodsWeightInfoDialog
import com.two.screen.water.balance.widget.keyboard.SearchKeyBoardViewHandler
import kotlinx.android.synthetic.main.activity_index.*
import me.grantland.widget.AutofitTextView
import java.math.BigDecimal
import java.util.concurrent.TimeUnit


@Route(path = ARouterUtils.IndexActivity)
class IndexActivity : BaseActivity() {
    /*布局、样式*/
    override fun getContentLayout(): Any = R.layout.activity_index

    /*列表适配器*/
    lateinit var mFoodAdapter: FoodAdapter
    lateinit var mHadChooseAdapter: HadChooseAdapter
    lateinit var mClassifyAdapter: ClassifyAdapter

    /*七华 称重状态*/
    private var mIsStable = true
    private var mHadRemovePeel = false
    private var mIsNetWeight = false
    private var mWeightNumber = 0.000

    /*以下是状态*/
    private var mIsAddNewHadOrder: Boolean = true           //这里 是否添加新的商品到购物车，目地过滤下一次使用计算器清空

    /*对话框*/
    private var mEditOrderGoodsWeightInfoDialog: EditOrderGoodsWeightInfoDialog? = null

    /*初始数据变量*/
    private var mTotalRealPrice: String? = null //总额-折扣= 实收金额
    private var mIsPendingOrder = false //是否进入挂单处理
    private var mPendingOrder: OrderDB? = null
    private var mLastOrderDB: OrderDB? = null

    private var mTotalList: List<CateDB>? = null//商品总数据
    private var mSearchList: MutableList<CateDB> = mutableListOf(CateDB().apply { isSelected = true;cateName = "搜索结果";productDBList = mutableListOf() })//搜索出来的商品数据
    private val mFloatTag = "键盘搜索"

    override fun beforeSetContentView() {
        ImmersionBar.with(this)
            //这了打算弄成配置,由于逻辑不通，不能做成那个。
            .hideBar(BarHide.FLAG_HIDE_BAR)
            //.keyboardEnable(true)
            .init()
    }

    override fun initView(savedInstanceState: Bundle?) {
        mWeightTv.typeface = Typeface.createFromAsset(assets, "DS-DIGIT-4.ttf")
    }

    override fun initData() {

        initClassify()
        initFoodRecyclerView()
        initOrderRcy()
        initLastTotalPrice()
        //PrintUtils.initPrint(this)
        //同步上传一下离线订单
        OrderApi.batchUploadCashOrder(this)
        initRightBottomInfo()
    }

    @SuppressLint("SetTextI18n")
    private fun initRightBottomInfo() {
        mShopNameTv.text = "商户名称:${DataApi.mShopName}"
        mStallNameTv.text = "档口号:${DataApi.mShopStallName}"
        mVersionNameTv.text = "版本:".plus(CommUtils.getAppVersionName().plus("::").plus(CommUtils.getAppUUidLast4()))
        initBtlPrinterIcon(SPUtils.getBoolean(Params.mIsShowBluetoothPrinter))
    }

    private fun initBtlPrinterIcon(isShow: Boolean) {
        mBluetoothPrinterIconIv.visibility = if (isShow) View.VISIBLE else View.GONE
    }

    @SuppressLint("SetTextI18n")
    private fun initLastTotalPrice() {
        var orderDB = OrderApi.getLastOrder()
        mLastTotalPriceTv.text = "上单收￥${if (orderDB == null) 0.00 else orderDB.totalPrice}"
        mLastOrderDB = orderDB
        mLastTotalPriceTv.setOnClickListener {
            PrinterAll.printOrder(PrintOrderBean.orderDB2PrintOrderBean(mLastOrderDB))
        }
    }

    private fun initClassify() {
        (mClassifyRecyclerView.itemAnimator as SimpleItemAnimator).supportsChangeAnimations = false //去闪烁
//        mClassifyRecyclerView?.addItemDecoration(
//            DividerItemDecoration(this, DividerItemDecoration.HORIZONTAL_LIST, 1, ContextCompat.getColor(App.context!!, R.color.c6), false)
//        )
        mClassifyAdapter = ClassifyAdapter()
        mClassifyRecyclerView.layoutManager = GridLayoutManager(this, 8)
        mClassifyRecyclerView.adapter = mClassifyAdapter

    }

    /*给分类设置数据*/
    private fun setNewData2CateList(mCateList: MutableList<CateDB>?) {
        val size = mCateList?.size ?: 0
        val params: ViewGroup.LayoutParams = mClassifyRecyclerView.layoutParams
        when (size) {
            in 0..8 -> params.height = resources.getDimensionPixelSize(R.dimen.index_top_height_x1)
            in 9..16 -> params.height = resources.getDimensionPixelSize(R.dimen.index_top_height_x2)
            else -> params.height = resources.getDimensionPixelSize(R.dimen.index_top_height_x3)
        }
        mClassifyRecyclerView.layoutParams = params
        mClassifyAdapter.setNewData(mCateList)
    }

    private fun initOrderRcy() {
        (mHadChooseRecyclerView.itemAnimator as SimpleItemAnimator).supportsChangeAnimations = false //去闪烁
        val size = resources.getDimensionPixelSize(R.dimen.common_measure_1dp)
        mHadChooseRecyclerView?.addItemDecoration(
            com.two.screen.water.balance.widget.DividerItemDecoration(
                this,
                com.two.screen.water.balance.widget.DividerItemDecoration.HORIZONTAL_LIST,
                CommUtils.dp2px(size),
                ContextCompat.getColor(App.context!!, R.color.c6),
                true
            )
        )
        mHadChooseAdapter = HadChooseAdapter()
        mHadChooseRecyclerView.layoutManager = LinearLayoutManager(this)
        mHadChooseRecyclerView.adapter = mHadChooseAdapter
        mHadChooseAdapter.bindToRecyclerView(mHadChooseRecyclerView)
        mHadChooseAdapter.setEmptyView(R.layout.layout_status_layout_manager_empty3)

        //读取缓存
        //mHadChooseAdapter.setNewData(mutableListOf(ProductDB(), ProductDB(), ProductDB(), ProductDB(), ProductDB(), ProductDB()))
    }

    private fun initFoodRecyclerView() {
        (mProductRecyclerView.itemAnimator as SimpleItemAnimator).supportsChangeAnimations = false //去闪烁
        mFoodAdapter = FoodAdapter()
        mProductRecyclerView.layoutManager = GridLayoutManager(this, 3)
        mProductRecyclerView.adapter = mFoodAdapter
        mFoodAdapter.bindToRecyclerView(mProductRecyclerView)
        mFoodAdapter.setEmptyView(R.layout.layout_status_layout_manager_empty1)


        var itemDragAndSwipeCallback = ItemDragAndSwipeCallback(mFoodAdapter);
        var itemTouchHelper = ItemTouchHelper(itemDragAndSwipeCallback)
        itemTouchHelper.attachToRecyclerView(mProductRecyclerView)
        mFoodAdapter.enableDragItem(itemTouchHelper)
        mFoodAdapter.setOnItemDragListener(object : OnItemDragListener {
            override fun onItemDragStart(viewHolder: RecyclerView.ViewHolder, pos: Int) {
                d("onItemDragStart->pos:$pos")
//                var list = mFoodAdapter.data
//                list.forEach {
//                    d("updateGoodsSort->移动前:productName:${it.productName},sort:${it.sort}")
//                }
            }

            override fun onItemDragMoving(source: RecyclerView.ViewHolder, from: Int, target: RecyclerView.ViewHolder?, to: Int) {
                d("onItemDragMoving->from:$from,to:$to")
            }

            override fun onItemDragEnd(viewHolder: RecyclerView.ViewHolder, pos: Int) {
                d("onItemDragEnd->pos:$pos")
//                var list = mFoodAdapter.data
//                list.forEach {
//                    d("updateGoodsSort->移动后:productName:${it.productName},sort:${it.sort}")
//                }
                updateGoodsSort()
            }
        })

        updateCateProduct()
    }

    /*查询本地数据库数据，更新UI */
    private fun updateCateProduct() {
        CateProductApi.queryCateData(this, object : ApiCallBack() {
            override fun success(t: Any?) {
                var tmpJson = t as String
                mTotalList = try {
                    CommUtils.gson.fromJson(tmpJson, object : TypeToken<List<CateDB>>() {}.type)
                } catch (e: Exception) {
                    null
                }
                mTotalList?.firstOrNull()?.isSelected = true
                recoverFoodsData()
            }
        })
    }

    private fun updateGoodsSort() {
        if (!DataApi.mIsConnectNet) return
        var list = mFoodAdapter.data

        var map = sortedMapOf<Long, Long>()
        list.indices.forEach { index ->
            val productDB = list[index]
            productDB.sort = index + 1L
            map[productDB.productId] = productDB.sort
        }

        val toJson = CommUtils.gson.toJson(map)
        d("updateGoodsSort->params:$toJson")

        NormalApi.postPay(sortedMapOf(Params.vals to toJson), Urls.goodsSort)
            .compose(RxUtils.aLifecycle(this))
            .compose(RxUtils.io())
            .subscribe(object : DialogObserver<ServerOrderResult>(this) {
                override fun onSuccessNext(t: BaseBean<out ServerOrderResult>) {
                    dataIsNull(t)
                }

                @SuppressLint("NotifyDataSetChanged")
                override fun dataIsNull(t: BaseBean<out ServerOrderResult>) {
                    CateProductApi.updateProductSort(list)
                    super.dataIsNull(t)
                }
            })
    }


    /*获取分类选中状态。*/
    private fun getCateSelectedPosition(): Int? {
        val cateList = mClassifyAdapter.data
        return cateList.indices.find { cateList[it].isSelected }
    }

    @SuppressLint("CheckResult")
    override fun initListener() {
        mGo2CollectMoneyLayout.setOnClickListener {
            val hadChooseProductList = mHadChooseAdapter.data
            if (hadChooseProductList.isNotEmpty()) {
                go2CollectMoney(hadChooseProductList)
            } else {
                ToastUtil.showToast("请选择商品!")
            }
        }

        mClearTv.setOnClickListener {
            if (mHadChooseAdapter.data.isEmpty())
                ARouter.getInstance()
                    .build(ARouterUtils.PendingOrderActivity)
                    .navigation()
            else {
                mHadChooseAdapter.setNewData(null)
                calcTotalPrice()
            }
        }

        mMenuLayout.setOnClickListener {
            ARouter.getInstance()
                .build(ARouterUtils.FunctionMenuActivity)
                .navigation()
        }

        RxView.clicks(mHangOrderTv)
            .throttleFirst(1, TimeUnit.SECONDS)
            .subscribe {
                val list = mHadChooseAdapter.data
                if (list.isNotEmpty()) {
                    if (mIsPendingOrder) {
                        mPendingOrder?.totalPrice = String.format("%.2f", mTotalRealPrice?.toDouble() ?: 0.0)
                        mPendingOrder?.realPrice = mPendingOrder?.totalPrice
                        OrderApi.updatePendingOrder(this, mPendingOrder, mHadChooseAdapter.data, object : ApiCallBack() {
                            override fun success(t: Any?) {
                                mPendingOrder = null
                                mIsPendingOrder = false
                                ToastUtil.showToast(t as String)
                                //清空商品
                                mHadChooseAdapter.setNewData(null)
                                calcTotalPrice()
                            }
                        })
                    } else {
                        var orderDB = OrderApi.createOrderDB(0.00, 100, mTotalRealPrice?.toDouble() ?: 0.0, mTotalRealPrice?.toDouble() ?: 0.0, PAY_TYPE_NONE, "未知", ORDER_TYPE_PENDING)
                        //更新挂单
                        OrderApi.saveOrderDB(orderDB, list)
                        //清空商品
                        mHadChooseAdapter.setNewData(null)
                        calcTotalPrice()
                    }
                } else {
                    ToastUtil.showToast("请选择商品!")
                }
            }
        mSearchLayout.setOnClickListener { initEasyFloat() }
    }

    private fun initEasyFloat() {
        //ToastUtil.showToast("isOpenFloat:$isOpenFloat")
        if (PermissionUtils.checkPermission(this)) {
            showEasyFloat()
        } else {
            AlertDialog.Builder(this)
                .setMessage("使用浮窗功能，需要您授权悬浮窗权限。")
                .setPositiveButton("去开启") { _, _ ->
                    showEasyFloat()
                }
                .setNegativeButton("取消") { _, _ -> }
                .show().apply {
                    DialogUtil.hideNavigationBar(this.window)
                }
        }
    }

    private var mSearchTv: TextView? = null
    private fun showEasyFloat() {
        if (EasyFloat.isShow(mFloatTag)) {
            mSearchTv = null
            EasyFloat.dismiss(mFloatTag)
            return
        }
//        App.screenWidth
//        -App.screenHeight
        EasyFloat.with(App.context!!)
            .setLayout(R.layout.float_index_search_key_board) { rootView ->
                var mRlSearchKeyboard = rootView.findViewById<RelativeLayout>(R.id.mRlSearchKeyboard)
                mSearchTv = rootView.findViewById<TextView>(R.id.mSearchTv)
                var mClearIv = rootView.findViewById<ImageView>(R.id.mClearIv)
                var mGoBackBtn = rootView.findViewById<ImageView>(R.id.mGoBackBtn)
                mClearIv.setOnClickListener {
                    mSearchTv?.text = ""
                    recoverFoodsData()
                }
                mGoBackBtn.setOnClickListener {
                    mSearchTv?.text = ""
                    recoverFoodsData()
                    EasyFloat.dismiss(mFloatTag)
                }
                var keyBoardViewHandler: SearchKeyBoardViewHandler = object : SearchKeyBoardViewHandler(mRlSearchKeyboard) {
                    override fun onTextChanged() {
                        var keywords: String = mSearchTv?.text.toString()
                        d("keywords:$keywords")
                        if (keywords.isNotBlank()) {
                            //查找商品
                            mSearchList.first().productDBList.clear()
                            mTotalList?.forEach { cateDB ->
                                cateDB.productDBList?.forEach { productDB ->
                                    if (productDB.pinYinName.contains(keywords)) mSearchList.first().productDBList.add(productDB)
                                }
                            }
                            setNewData2CateList(mSearchList)
                            mFoodAdapter.setNewData(mSearchList.first().productDBList)
                        } else {
                            recoverFoodsData()
                        }
                    }
                }
                keyBoardViewHandler.setInputTextView(mSearchTv)
            }
            .setTag(mFloatTag)
            .setShowPattern(ShowPattern.FOREGROUND)
            .setGravity(Gravity.BOTTOM or Gravity.END)
            //.setLocation(/*mSearchLayout.x.toInt() + mSearchLayout.width / 2*/0, /*mSearchLayout.bottom + mSearchLayout.height*/0)
            .setAnimator(null)
            .show()
    }

    /*恢复商品原有数据*/
    private fun recoverFoodsData() {
        setNewData2CateList(mTotalList?.toMutableList())
        getCateSelectedPosition()?.let {
            mFoodAdapter.setNewData(mClassifyAdapter.data[it].productDBList)
        }
    }

    //跳转收银界面
    private fun go2CollectMoney(hadChooseProductList: MutableList<OrderProductDB>) {
        var dataJson = CommUtils.gson.toJson(CollectMoneyBean().apply {
            goodsList = hadChooseProductList
            totalPrice = this@IndexActivity.mTotalRealPrice
            pendingOrder = mPendingOrder
        })
        ARouter.getInstance()
            .build(ARouterUtils.CollectMoneyActivity)
            .withString("mDataJson", dataJson)
            .navigation()
    }

    /*购物车列表 适配器*/
    inner class ClassifyAdapter : BaseQuickAdapter<CateDB, BaseViewHolder>(R.layout.item_index_classify, null) {
        @SuppressLint("CheckResult", "NotifyDataSetChanged")
        override fun convert(helper: BaseViewHolder, item: CateDB) {
            helper.getView<TextView>(R.id.item_tv1).apply {
                this.text = item.cateName
                this.isSelected = item.isSelected
                typeface = if (item.isSelected) Typeface.DEFAULT_BOLD else Typeface.DEFAULT;
                setOnClickListener {
                    var index = data.indices.find { data[it].isSelected }
                    index?.let {
                        data[index].isSelected = false
                        notifyItemChanged(index)
                    }
                    //data.forEach { it.isSelected = false }
                    val position = helper.bindingAdapterPosition
                    val cateDB = data[position]
                    cateDB.isSelected = true
                    notifyItemChanged(position)
                    //notifyDataSetChanged()
                    //TODO:刷新商品数据
                    mFoodAdapter.setNewData(cateDB.productDBList)
                }
            }
        }
    }

    /*购物车列表 适配器*/
    inner class HadChooseAdapter : BaseQuickAdapter<OrderProductDB, BaseViewHolder>(R.layout.item_order_list, null) {
        @SuppressLint("CheckResult")
        override fun convert(helper: BaseViewHolder, item: OrderProductDB) {
            var realPrice = try {
                String.format("%.2f", item.realPrice?.toDouble())
            } catch (e: Exception) {
                "0.00"
            }
            helper
                .setText(R.id.item_tv1, String.format("%02d", helper.bindingAdapterPosition + 1)/*.plus(".")*/)
                .setText(R.id.item_atv1, item.productName)
                .setText(R.id.item_atv2, item.weight ?: "0.000")
                .setText(R.id.item_atv3, "￥".plus(realPrice))
                .setText(R.id.item_atv4, "小计：".plus(item.subTotalPrice ?: "0.00"))
                .setText(R.id.item_atv5, "折扣：".plus(item.giftPrice ?: "0.00"))
                .setGone(R.id.item_atv5, item.discountPercent != 100)

            /*购物车编辑商品*/
            helper.getView<View>(R.id.item_root_view).apply {
                //#EDF6FC #C9E2F3
                setBackgroundColor(if (helper.bindingAdapterPosition == data.size - 1) CommUtils.getColor(R.color.GC9E2F3) else CommUtils.getColor(R.color.GEDF6FC))
                RxView.clicks(this)
                    .throttleFirst(1, TimeUnit.SECONDS)
                    .subscribe {
                        var orderProductDB = mData[helper.bindingAdapterPosition]
                        mEditOrderGoodsWeightInfoDialog = EditOrderGoodsWeightInfoDialog(this@IndexActivity)
                        mEditOrderGoodsWeightInfoDialog?.show()
                        mEditOrderGoodsWeightInfoDialog?.setEditGoodsInfoListener(object : EditOrderGoodsWeightInfoDialog.EditGoodsInfoDialogListener {
                            @SuppressLint("NotifyDataSetChanged")
                            override fun onConfirm(item: OrderProductDB, mIsSamePrice: Boolean) {
                                mHadChooseAdapter.notifyDataSetChanged()
                                calcTotalPrice()
                                updateOnlinePrice(item, mIsSamePrice)
                            }
                        })
                        d("unit_type:${orderProductDB.unitType}")
                        mEditOrderGoodsWeightInfoDialog?.setGoodsInfo(orderProductDB)
//                        when (orderProductDB.unitType) {
//                            UNIT_TYPE_TIMES -> {
//                                mEditOrderGoodsTimesInfoDialog = EditOrderGoodsTimesInfoDialog(this@IndexActivity)
//                                mEditOrderGoodsTimesInfoDialog?.show()
//                                mEditOrderGoodsTimesInfoDialog?.setEditGoodsInfoListener(object : EditOrderGoodsTimesInfoDialog.EditGoodsInfoDialogListener {
//                                    @SuppressLint("NotifyDataSetChanged")
//                                    override fun onConfirm(item: OrderProductDB, mIsSamePrice: Boolean) {
//                                        mHadChooseAdapter.notifyDataSetChanged()
//                                        calcTotalPrice()
//                                        updateOnlinePrice(item, mIsSamePrice)
//                                    }
//                                })
//                                mEditOrderGoodsTimesInfoDialog?.setGoodsInfo(orderProductDB)
//
//                            }
//                            else -> {
//                                mEditOrderGoodsWeightInfoDialog = EditOrderGoodsWeightInfoDialog(this@IndexActivity)
//                                mEditOrderGoodsWeightInfoDialog?.show()
//                                mEditOrderGoodsWeightInfoDialog?.setEditGoodsInfoListener(object : EditOrderGoodsWeightInfoDialog.EditGoodsInfoDialogListener {
//                                    @SuppressLint("NotifyDataSetChanged")
//                                    override fun onConfirm(item: OrderProductDB, mIsSamePrice: Boolean) {
//                                        mHadChooseAdapter.notifyDataSetChanged()
//                                        calcTotalPrice()
//                                        updateOnlinePrice(item, mIsSamePrice)
//                                    }
//                                })
//                                d("unit_type:${orderProductDB.unitType}")
//                                mEditOrderGoodsWeightInfoDialog?.setGoodsInfo(orderProductDB)
//                            }
//                        }
                        dismissEasyFloat()
                    }
            }

            /*购物车删除商品*/
            helper.getView<ImageView>(R.id.item_del_iv).apply {
                RxView.clicks(this)
                    .throttleFirst(1, TimeUnit.SECONDS)
                    .subscribe {
                        mHadChooseAdapter.remove(helper.bindingAdapterPosition)
                        calcTotalPrice()
                        /*至少有1条以上，而且点击最后一条删除，需要刷新倒数第二条*/
                        if (data.size > 0) mHadChooseAdapter.notifyItemChanged(data.size - 1)
                    }
            }
        }
    }

    private fun updateOnlinePrice(item: OrderProductDB, mIsSamePrice: Boolean) {
        d("updateOnlinePrice->mPriceBefore:${item.realPrice?.toDouble()},mIsSamePrice:$mIsSamePrice,")
        if (!DataApi.mIsConnectNet) return
        if (mIsSamePrice) return
        NormalApi.postPay(sortedMapOf(Params.id to item.productId, Params.price to item.realPrice, Params.item_type to (item.unitType + 1)), Urls.goodsUpPrice)
            .compose(RxUtils.aLifecycle(this))
            .compose(RxUtils.io())
            .subscribe(object : DialogObserver<ServerOrderResult>(this) {
                override fun onSuccessNext(t: BaseBean<out ServerOrderResult>) {
                    dataIsNull(t)
                }

                @SuppressLint("NotifyDataSetChanged")
                override fun dataIsNull(t: BaseBean<out ServerOrderResult>) {
                    mTotalList?.forEach { cate ->
                        var p = cate.getProductDBList()?.find { item.productId == it.productId }
                        if (p != null) {
                            p.realPrice = item.realPrice
                            p.oriPrice = item.realPrice
                            p.unitType = item.unitType
                            App.mDaoSession?.productDBDao?.update(p)
                            return@forEach
                        }
                    }
                    mFoodAdapter.notifyDataSetChanged()
                    super.dataIsNull(t)
                }
            })

    }

    /*商品列表 适配器*/
    inner class FoodAdapter : BaseItemDraggableAdapter<ProductDB, BaseViewHolder>(R.layout.item_index_good_info, null) {
        @SuppressLint("CheckResult", "NotifyDataSetChanged")
        override fun convert(helper: BaseViewHolder, item: ProductDB) {
            helper.getView<AutofitTextView>(R.id.item_atv1).text = item.productName
            helper.getView<AutofitTextView>(R.id.item_atv2).text = "￥".plus(item.oriPrice).plus(if (item.unitName != null && item.unitName!!.isNotBlank()) "/${item.unitName}" else "/公斤")
            var choseIv = helper.getView<ImageView>(R.id.item_choose_iv)
            helper.setGone(R.id.item_tv3, item.unitType == UNIT_TYPE_TIMES)
            helper.getView<TextView>(R.id.item_tv4).apply {
                visibility = if (DataApi.mUseSimpleInventory && DataApi.mIsConnectNet) View.VISIBLE else View.GONE
                text = "库存：".plus(item.invNum)
            }
            helper.getView<View>(R.id.item_root_view).apply {
                RxView.clicks(this)
                    .throttleFirst(500, TimeUnit.MILLISECONDS)
                    .subscribe {
                        /*把商品添加到购物车列表*/
                        if (item.unitType != UNIT_TYPE_TIMES) {
                            if (mWeightNumber <= 0) {
                                ToastUtil.showToast("重量需要大于0!")
                                return@subscribe
                            }
                            if (!mIsStable) {
                                ToastUtil.showToast("当前称重不稳定!")
                                return@subscribe
                            }
                        }
                        onGoodsItemClick(item)
                    }
            }
            /*商品图片*/
            helper.getView<ImageView>(R.id.item_iv)
                .apply {
                    if (item.logoImage != null && item.logoImage!!.isNotBlank()) {
                        ImageManger.setCenterCropImg(context, item.logoImage, this)
                    } else {
                        setImageResource(R.drawable.empty_food_default1)
                    }
                }
        }
    }

    private fun onGoodsItemClick(item: ProductDB) {
        updateOrderTraceQrUrl()
        val newItem = CommUtils.gson.fromJson(CommUtils.gson.toJson(item), OrderProductDB::class.java)
        newItem.oriPrice = item.oriPrice
        val weight = mWeightTv.text.toString()
        newItem.weight = if (newItem.unitType == UNIT_TYPE_TIMES) "1" else weight
        newItem.subTotalPrice = String.format(
            "%.2f", try {
                BigDecimal(newItem.weight).multiply(BigDecimal(newItem.oriPrice)).toDouble()
            } catch (e: Exception) {
                0.0
            }
        )
        mHadChooseAdapter.addData(newItem)
        val position = mHadChooseAdapter.data.size - 1
        if (position != 0) {
            /*第一条不用滚动，以及刷新*/
            mHadChooseRecyclerView.scrollToPosition(position)
            /*这条刷新前面那个条目，衬托新的条目被选中意思*/
            mHadChooseAdapter.notifyItemChanged(position - 1)
        }
        calcTotalPrice()
        mIsAddNewHadOrder = true
    }

    /*计算总计*/
    @SuppressLint("SetTextI18n")
    private fun calcTotalPrice() {
        //var total = 0.0
        var totalPrice = BigDecimal(0.0)
        var realPrice = BigDecimal(0.0)
        var giftPrice = BigDecimal(0.0)
        val list = mHadChooseAdapter.data
        list.forEach {
            totalPrice = try {
                val d2 = it.realPrice.toDouble()
                val d1 = it.weight.toDouble()
                UtilsBigDecimal.add(totalPrice, UtilsBigDecimal.mul(d2, d1).toDouble())
            } catch (e: Exception) {
                ToastUtil.showToast("计算错误:${e.toString()}")
                return@calcTotalPrice
            }
            realPrice = try {
                val d1 = it.weight.toDouble()
                val d2 = it.realPrice.toDouble() * it.discountPercent / 100.0
                UtilsBigDecimal.add(realPrice, UtilsBigDecimal.mul(d1, d2).toDouble())
            } catch (e: Exception) {
                ToastUtil.showToast("计算错误:${e.toString()}")
                return@calcTotalPrice
            }
            giftPrice = try {
                val d1 = it.giftPrice.toDouble()
                UtilsBigDecimal.add(giftPrice, d1)
            } catch (e: Exception) {
                ToastUtil.showToast("计算错误:${e.toString()}")
                return@calcTotalPrice
            }
        }
        d("realPrice:${realPrice}")
        d("giftPrice:${giftPrice}")

        //折扣
        if (giftPrice.toDouble() > 0.0) {
            mDiscountPercentLayout.visibility = View.VISIBLE
            mDiscountPercentTv.text = String.format("%.2f", giftPrice)   //折扣金额
        } else {
            mDiscountPercentLayout.visibility = View.GONE
        }
        mTotalRealPrice = String.format("%.2f", realPrice)
        mTotalProductNumberTv.text = "${list.size}"
        mTotalPriceTv.text = String.format("%.2f", totalPrice)  //总金额
        //TODO:收银 = 总额 - 优惠。 所以购物车应该还需要呈现 优惠。
        mCollectMoneyTv.text = "￥${mTotalRealPrice}" //实收金额
        mClearTv.text = if (list.isEmpty()) "取单" else "清空(${list.size})"
        mHangOrderTv.text = if (mIsPendingOrder) "更新挂单" else "挂单"
        EventBusUtil.sendEvent(Event(if (list.size > 0) EventCode.VICE_SCREEN_STATUS_NO_AWAIT else EventCode.VICE_SCREEN_STATUS_YES_AWAIT, 0))

        //刷新 副屏的UI 。
        val orderProductDB = mHadChooseAdapter.data.lastOrNull()
        EventBusUtil.sendEvent(Event(EventCode.VICE_SCREEN_UPDATE_DATA, ViceBean().apply {
            this.curName = orderProductDB?.productName ?: "暂无"
            this.unitPrice = orderProductDB?.realPrice ?: "0.00"
            this.totalPrice = mTotalRealPrice
            this.list = mHadChooseAdapter.data
        }))
    }

    /*更新副屏的溯源地址以及动、静态二维码刷新*/
    private fun updateOrderTraceQrUrl() {
        EventBusUtil.sendEvent(Event(EventCode.ORDER_UPDATE_TRACE_URL, ResponsePay()))
    }

    override fun doubleQuit(): Boolean = true
    override fun exit(): Boolean {
        try {
            if (isExit) {
                stopService(Intent(this, AppService::class.java))
            }
        } catch (e: Exception) {
            d("退出失败:$e")
        }
        return super.exit()
    }

    override fun isRegisterEventBus(): Boolean = true

    @SuppressLint("SetTextI18n")
    override fun receiveEvent(event: Event<Any>) {
        super.receiveEvent(event)
        when (event.code) {
            PENDING_ORDER_COLLECT_MONEY -> {//取单，返回再跳转去收银
                mIsPendingOrder = true
                mPendingOrder = event.data as OrderDB
                mHadChooseAdapter.setNewData(
                    try {
                        mPendingOrder?.orderProductDBList
                    } catch (e: Exception) {
                        null
                    }
                )
                calcTotalPrice()
                go2CollectMoney(mHadChooseAdapter.data)
            }
            PENDING_ORDER_EDIT_AGAIN -> {//取单，再次编辑挂单
                mIsPendingOrder = true
                mPendingOrder = event.data as OrderDB
                mHadChooseAdapter.setNewData(
                    try {
                        mPendingOrder?.orderProductDBList
                    } catch (e: Exception) {
                        null
                    }
                )
                calcTotalPrice()
            }
            COLLECT_MONEY_SUCCESS -> {//收银成功后刷新
                mIsPendingOrder = false
                mPendingOrder = null
                mHadChooseAdapter.setNewData(null)
                calcTotalPrice()
                initLastTotalPrice()
                CateProductApi.updateCateProductData(this, object : ApiCallBack() {
                    override fun success() {
                        updateCateProduct()
                    }
                })
            }
            WEIGHT_DATA_ALL -> {//称重数据
                var weightData = event.data as WeightBean
                mWeightTv.setTextColor(CommUtils.getColor(R.color.red_count_num))
                mWeightTv.text = weightData.weightString
                mStableIv.setImageResource(if (mIsStable) R.drawable.shape_gradient_green_r100 else R.drawable.shape_grey_999999_8r)
                if (true == mEditOrderGoodsWeightInfoDialog?.isShowing) {
                    mWeightTv.text = "0.00"
                    mWeightTv.setTextColor(CommUtils.getColor(R.color.c6))
                    hideSoftKeyBoard()
                } else {
                    mWeightTv.setTextColor(CommUtils.getColor(R.color.red_count_num))
                }
                EventBusUtil.sendEvent(Event(EventCode.VICE_SCREEN_WEIGHT_NUMBER, mWeightTv.text.toString()))
                /*重量大于0 退出待机*/
                if (mWeightNumber > 0) EventBusUtil.sendEvent(Event(EventCode.VICE_SCREEN_STATUS_NO_AWAIT, mWeightTv.text.toString()))
            }
            AI_RETURN_INFO -> onGoodsItemClick(event.data as ProductDB)
            EventCode.FINISH_INDEX -> finish()
            EventCode.NET_WORK_STATUES -> initNetworkInfo()
            EventCode.BLUETOOTH_PRINT_IS_SHOW -> initBtlPrinterIcon(event.data as Boolean)
            EventCode.BLUETOOTH_PRINT_OPEN_CONNECTING -> mBluetoothPrinterIconIv.setImageResource(R.drawable.ic_ble_connecting)
            EventCode.BLUETOOTH_PRINT_OPEN_FAILED -> mBluetoothPrinterIconIv.setImageResource(R.drawable.ic_ble_connected_failed)
            EventCode.BLUETOOTH_PRINT_OPEN_SUCCESS -> mBluetoothPrinterIconIv.setImageResource(R.drawable.ic_ble_connect_success)
            EventCode.BATTERY_CHANGED_REGISTER -> mBatteryNumTv.visibility = View.VISIBLE
            EventCode.BATTERY_CHANGED_UNREGISTER -> mBatteryNumTv.visibility = View.GONE
            else -> {}
        }
    }

    @SuppressLint("SetTextI18n")
    private fun initNetworkInfo() {
        when (NetworkUtils.getNetworkType()) {
            NetworkUtils.NetworkType.NETWORK_ETHERNET -> {
                mConnectStatusTv.visibility = View.GONE
                mConnectWifiStatusIv.visibility = View.GONE
                mConnectEtherNetStatusIv.visibility = View.VISIBLE
                mConnectEtherNetStatusIv.setImageResource(if (DataApi.mIsConnectNet) R.drawable.ic_network_ok else R.drawable.ic_network_off)
            }
            NetworkUtils.NetworkType.NETWORK_WIFI -> {
                mConnectStatusTv.visibility = View.GONE
                mConnectEtherNetStatusIv.visibility = View.GONE
                mConnectWifiStatusIv.visibility = View.VISIBLE
                mConnectWifiStatusIv.setImageResource(if (DataApi.mIsConnectNet) R.drawable.ic_wifi_ok else R.drawable.ic_wifi_off)
            }
            NetworkUtils.NetworkType.NETWORK_5G -> {
                mConnectWifiStatusIv.visibility = View.GONE
                mConnectEtherNetStatusIv.visibility = View.GONE
                mConnectStatusTv.visibility = View.VISIBLE
                mConnectStatusTv.text = "5G"
                mConnectStatusTv.setTextColor(CommUtils.getColor(if (DataApi.mIsConnectNet) R.color.f6 else R.color.red_FF0000))
            }
            NetworkUtils.NetworkType.NETWORK_4G -> {
                mConnectWifiStatusIv.visibility = View.GONE
                mConnectEtherNetStatusIv.visibility = View.GONE
                mConnectStatusTv.visibility = View.VISIBLE
                mConnectStatusTv.text = "4G"
                mConnectStatusTv.setTextColor(CommUtils.getColor(if (DataApi.mIsConnectNet) R.color.f6 else R.color.red_FF0000))
            }
            NetworkUtils.NetworkType.NETWORK_3G -> {
                mConnectWifiStatusIv.visibility = View.GONE
                mConnectEtherNetStatusIv.visibility = View.GONE
                mConnectStatusTv.visibility = View.VISIBLE
                mConnectStatusTv.text = "3G"
                mConnectStatusTv.setTextColor(CommUtils.getColor(if (DataApi.mIsConnectNet) R.color.f6 else R.color.red_FF0000))
            }
            else -> {
                if (!mConnectWifiStatusIv.isVisible && !mConnectEtherNetStatusIv.isVisible && !mConnectStatusTv.isVisible) {
                    mConnectWifiStatusIv.visibility = View.VISIBLE
                }
                mConnectEtherNetStatusIv.setImageResource(if (DataApi.mIsConnectNet) R.drawable.ic_network_ok else R.drawable.ic_network_off)
                mConnectWifiStatusIv.setImageResource(if (DataApi.mIsConnectNet) R.drawable.ic_wifi_ok else R.drawable.ic_wifi_off)
                mConnectStatusTv.setTextColor(CommUtils.getColor(if (DataApi.mIsConnectNet) R.color.f6 else R.color.red_count_num))
//                mConnectStatusIv.visibility = View.GONE
//                mConnectStatusTv.visibility = View.GONE
            }
        }

    }

    override fun receiveStickyEvent(event: Event<Any>) {
        super.receiveStickyEvent(event)
        when (event.code) {
            EventCode.BATTERY_CHANGED_DATA -> initBatteryInfo(event.data as BatteryChangedBean)
            else -> {}
        }
    }

    @SuppressLint("SetTextI18n")
    private fun initBatteryInfo(batteryChangedBean: BatteryChangedBean) {
        mBatteryNumTv.visibility = View.VISIBLE
        when (batteryChangedBean.status) {
            BatteryManager.BATTERY_STATUS_CHARGING -> mBatteryNumTv.text = "充电中:${batteryChangedBean.num}%"
            BatteryManager.BATTERY_STATUS_DISCHARGING -> mBatteryNumTv.text = "电池供电:${batteryChangedBean.num}%"
            BatteryManager.BATTERY_STATUS_FULL -> mBatteryNumTv.text = "充满:${batteryChangedBean.num}%"
            BatteryManager.BATTERY_STATUS_UNKNOWN -> mBatteryNumTv.text = "有线供电:${batteryChangedBean.num}%"
            else -> {
//                mBatteryStatusIv.visibility = View.GONE
                mBatteryNumTv.visibility = View.GONE
            }
        }
    }

    override fun onPause() {
        dismissEasyFloat()
        super.onPause()
    }

    private fun dismissEasyFloat() {
        if (EasyFloat.isShow(mFloatTag)) {
            mSearchTv?.text = ""
            mSearchTv = null
            EasyFloat.dismiss(mFloatTag)
            recoverFoodsData()
        }
    }

    override fun onDestroy() {
        d("AiAll->IndexActivity-onDestroy")
        super.onDestroy()
    }
}











